<template>
    <div>
        <div ref="editor" style="text-align:left;margin: 5px;width: 100%">
        </div>
    </div>
</template>

<script>
    import E from "wangeditor";
    import {uploadFile, BASE_URL} from "../../../api";

    export default {
        name: "editor",
        data() {
            return {
                editor: null
            }
        },
        watch: {
            content: function(val) {
                this.editor.txt.html(val);
                // this.editor.txt.html(val)
            }
        },
        props: {
            content: String
        },
        mounted() {
            this.initEditor();
        },
        methods: {
            initEditor() {
                this.editor = new E(this.$refs.editor);
                this.editor.customConfig.onchange = html => {
                    this.info = html;
                    this.$emit("change", this.info);
                };

                this.editor.customConfig.customUploadImg = async function (files, insert) {
                    // files 是 input 中选中的文件列表
                    // insert 是获取图片 url 后，插入到编辑器的方法
                    // eslint-disable-next-line no-console
                    console.log(files, "files");
                    // let imagesDetail = [];
                    for (let index in files) {
                        let formData = new FormData();
                        formData.append("image", files[index]);
                        let imgRes = await uploadFile(formData);
                        // eslint-disable-next-line no-console
                        console.log(imgRes, "imgRes");
                        // 上传代码返回结果之后，将图片插入到编辑器中
                        insert(BASE_URL + "/" + imgRes.url);
                        // imagesDetail.push({file: imgRes.url})
                    }
                };
                this.editor.create();
                this.editor.txt.html(this.content);
            }
        }
    }
</script>

<style scoped lang="stylus" ref="stylesheet/stylus">

</style>
